﻿using AutoMapper;
using Common.Damin;
using Common.Infrastructrue.Interface;
using Common.Service;
using MediatR;
using RabitPart.WritedPartApi.Application.Comman.RBACfiless;
using System.Transactions;

namespace RabitPart.WritedPartApi.Application.CommanHandel.RBACfiless
{
    public class RBACrolepermCreateCommanHandel : IRequestHandler<RBACrolepermCreateComman, ApiResult>
    {
        private readonly IRelrolepermResponsstity rolepermRE;
        private readonly IMapper _mapper;
        private readonly ILogger<RBACrolepermCreateCommanHandel> logger;
        public RBACrolepermCreateCommanHandel(IRelrolepermResponsstity rolepermRE, IMapper mapper, ILogger<RBACrolepermCreateCommanHandel> logger)
        {
            _mapper = mapper; 
            this.rolepermRE = rolepermRE;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(RBACrolepermCreateComman request, CancellationToken cancellationToken)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    var userrole = _mapper.Map<Rel_role_perm>(request);
                    userrole.CreateDate = DateTime.Now;
                    userrole.CreateOperatorName = "用户权限添加";
                    await rolepermRE.InsertAsync(userrole);
                    //提交事务
                    scope.Complete();
                    return ApiResult.Success(StatusCodeEnum.Ok);
                }
                finally
                {
                    //事务回滚
                    scope.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger.LogError("添加用户异常" + ex.Message);
                return await Task.FromResult(ApiResult.Fail(ex.Message, StatusCodeEnum.Fail));
            }
        }

    }
}
